<template>
  <div class="portfolio-container">
    <!-- 顶部标题栏 -->
    <div class="header">
      <h1 class="title">我的持仓</h1>
      <button class="refresh-btn" @click="refreshData" :disabled="loading">
        <svg class="refresh-icon" :class="{ 'spinning': loading }" viewBox="0 0 24 24" fill="none" stroke="currentColor">
          <path d="M23 4v6h-6M1 20v-6h6M20.49 9A9 9 0 0 0 5.64 5.64L1 10m22 4a9 9 0 0 1-14.85 4.36L23 14"/>
        </svg>
      </button>
    </div>

    <!-- 总览卡片 -->
    <div class="summary-card">
      <div class="summary-item">
        <span class="summary-label">持仓股票</span>
        <span class="summary-value">{{ heldStocks }}只</span>
      </div>
      <div class="summary-item">
        <span class="summary-label">总盈亏</span>
        <span class="summary-value" :class="totalProfitClass">
          {{ formatAmount(totalProfit) }}
        </span>
      </div>
    </div>

    <!-- 筛选标签 -->
    <div class="filter-tabs">
      <button
          v-for="tab in filterTabs"
          :key="tab.key"
          class="filter-tab"
          :class="{ 'active': activeFilter === tab.key }"
          @click="setFilter(tab.key)"
      >
        {{ tab.label }}
      </button>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <div class="loading-spinner"></div>
      <span class="loading-text">加载中...</span>
    </div>

    <!-- 持仓列表 -->
    <div v-else-if="filteredPortfolio.length > 0" class="portfolio-list">
      <div
          v-for="stock in filteredPortfolio"
          :key="stock.stockSymbol"
          class="stock-item"
          @click="showStockDetail(stock)"
      >
        <!-- 股票信息 -->
        <div class="stock-header">
          <div class="stock-symbol">{{ stock.stockSymbol }}</div>
          <div class="stock-status" :class="getStatusClass(stock)">
            {{ getStatusText(stock) }}
          </div>
        </div>

        <!-- 持仓数据 -->
        <div class="stock-data">
          <div class="data-item">
            <span class="data-label">持有数量</span>
            <span class="data-value">{{ stock.totalQuantity }}股</span>
          </div>
          <div class="data-item">
            <span class="data-label">{{ stock.total_buy_amount >= 0 ? '总成本' : '净收益' }}</span>
            <span class="data-value" :class="getAmountClass(stock.total_buy_amount)">
              {{ formatAmount(Math.abs(stock.total_buy_amount)) }}
            </span>
          </div>
        </div>

        <!-- 箭头指示器 -->
        <div class="arrow-indicator">
          <svg viewBox="0 0 24 24" fill="none" stroke="currentColor">
            <path d="M9 18l6-6-6-6"/>
          </svg>
        </div>
      </div>
    </div>

    <!-- 空状态 -->
    <div v-else class="empty-state">
      <svg class="empty-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor">
        <circle cx="12" cy="12" r="10"/>
        <path d="M16 16s-1.5-2-4-2-4 2-4 2"/>
        <line x1="9" y1="9" x2="9.01" y2="9"/>
        <line x1="15" y1="9" x2="15.01" y2="9"/>
      </svg>
      <p class="empty-text">{{ getEmptyText() }}</p>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import {getUserStockSummary} from "@/api/user/userget";
import toast from "@/utils/toast";
// 响应式数据
const portfolio = ref([])
const loading = ref(false)
const activeFilter = ref('all')

// 筛选选项
const filterTabs = [
  { key: 'all', label: '全部' },
  { key: 'holding', label: '持有中' },
  { key: 'sold', label: '已卖出' }
]

// 计算属性
const filteredPortfolio = computed(() => {
  switch (activeFilter.value) {
    case 'holding':
      return portfolio.value.filter(stock => stock.totalQuantity > 0)
    case 'sold':
      return portfolio.value.filter(stock => stock.totalQuantity === 0)
    default:
      return portfolio.value
  }
})

const heldStocks = computed(() => {
  return portfolio.value.filter(stock => stock.totalQuantity > 0).length
})

const totalProfit = computed(() => {
  return portfolio.value.reduce((sum, stock) => {
    return sum + (stock.total_buy_amount < 0 ? Math.abs(stock.total_buy_amount) : -stock.total_buy_amount)
  }, 0)
})

const totalProfitClass = computed(() => {
  if (totalProfit.value > 0) return 'profit'
  if (totalProfit.value < 0) return 'loss'
  return ''
})

// 方法
const fetchPortfolioData = async () => {
  loading.value = true
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    const {data}=await getUserStockSummary()
    portfolio.value = data
  } catch (error) {
    toast.error(error)
  } finally {
    loading.value = false
  }
}

const refreshData = () => {
  fetchPortfolioData()
}

const setFilter = (filterKey) => {
  activeFilter.value = filterKey
}

const getStatusClass = (stock) => {
  if (stock.totalQuantity > 0) return 'holding'
  return 'sold'
}

const getStatusText = (stock) => {
  if (stock.totalQuantity > 0) return '持有中'
  return '已卖出'
}

const getAmountClass = (amount) => {
  if (amount < 0) return 'profit'
  return 'cost'
}

const formatAmount = (amount) => {
  return new Intl.NumberFormat('zh-CN', {
    style: 'currency',
    currency: 'CNY',
    minimumFractionDigits: 0,
    maximumFractionDigits: 0
  }).format(amount)
}

const getEmptyText = () => {
  switch (activeFilter.value) {
    case 'holding':
      return '暂无持有中的股票'
    case 'sold':
      return '暂无已卖出的股票'
    default:
      return '暂无持仓数据'
  }
}
import router from "@/router";
const showStockDetail = (stock) => {
  router.push({
    path: '/center/stockInformation',
    query: {
      stockSymbol: stock.stockSymbol,
      stockNumber: stock.stockNumber
    }
  })
}
import {useTokenStore} from "@/stores/token";
// 生命周期
onMounted(() => {
  if(useTokenStore().hasToken){
    fetchPortfolioData()
  }
  else {
    toast.warning("请先登录")
    router.push('/user/auth')
  }

})
</script>

<style scoped>
.portfolio-container {
  min-height: 100vh;
  background-color: #000;
  color: #fff;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
  padding: 0 16px;
  padding-bottom: 80px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 0;
  border-bottom: 1px solid #333;
}

.title {
  font-size: 24px;
  font-weight: 600;
  margin: 0;
}

.refresh-btn {
  background: none;
  border: 1px solid #444;
  border-radius: 8px;
  padding: 8px;
  color: #fff;
  cursor: pointer;
  transition: all 0.2s;
}

.refresh-btn:hover:not(:disabled) {
  border-color: #666;
  background-color: #111;
}

.refresh-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.refresh-icon {
  width: 20px;
  height: 20px;
}

.refresh-icon.spinning {
  animation: spin 1s linear infinite;
}

@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

.summary-card {
  background-color: #111;
  border-radius: 12px;
  padding: 20px;
  margin: 20px 0;
  display: flex;
  justify-content: space-around;
}

.summary-item {
  text-align: center;
}

.summary-label {
  display: block;
  font-size: 14px;
  color: #999;
  margin-bottom: 8px;
}

.summary-value {
  display: block;
  font-size: 18px;
  font-weight: 600;
}

.summary-value.profit {
  color: #4ade80;
}

.summary-value.loss {
  color: #f87171;
}

.filter-tabs {
  display: flex;
  gap: 1px;
  background-color: #333;
  border-radius: 8px;
  padding: 4px;
  margin-bottom: 20px;
}

.filter-tab {
  flex: 1;
  background: none;
  border: none;
  color: #999;
  padding: 12px;
  border-radius: 6px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.2s;
}

.filter-tab.active {
  background-color: #fff;
  color: #000;
}

.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 0;
}

.loading-spinner {
  width: 32px;
  height: 32px;
  border: 3px solid #333;
  border-top: 3px solid #fff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 16px;
}

.loading-text {
  color: #999;
}

.portfolio-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.stock-item {
  background-color: #111;
  border-radius: 12px;
  padding: 16px;
  cursor: pointer;
  transition: all 0.2s;
  position: relative;
  display: flex;
  flex-direction: column;
}

.stock-item:hover {
  background-color: #1a1a1a;
}

.stock-item:active {
  transform: scale(0.98);
}

.stock-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.stock-symbol {
  font-size: 18px;
  font-weight: 600;
}

.stock-status {
  font-size: 12px;
  padding: 4px 8px;
  border-radius: 12px;
  border: 1px solid;
}

.stock-status.holding {
  color: #4ade80;
  border-color: #4ade80;
  background-color: rgba(74, 222, 128, 0.1);
}

.stock-status.sold {
  color: #94a3b8;
  border-color: #94a3b8;
  background-color: rgba(148, 163, 184, 0.1);
}

.stock-data {
  display: flex;
  justify-content: space-between;
}

.data-item {
  display: flex;
  flex-direction: column;
}

.data-label {
  font-size: 12px;
  color: #999;
  margin-bottom: 4px;
}

.data-value {
  font-size: 16px;
  font-weight: 600;
}

.data-value.profit {
  color: #4ade80;
}

.data-value.cost {
  color: #f87171;
}

.arrow-indicator {
  position: absolute;
  right: 16px;
  top: 50%;
  transform: translateY(-50%);
  color: #666;
}

.arrow-indicator svg {
  width: 16px;
  height: 16px;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  text-align: center;
}

.empty-icon {
  width: 64px;
  height: 64px;
  color: #333;
  margin-bottom: 16px;
}

.empty-text {
  color: #999;
  font-size: 16px;
  margin: 0;
}

/* 响应式设计 */
@media (max-width: 480px) {
  .portfolio-container {
    padding: 0 12px;
  }

  .summary-card {
    margin: 16px 0;
    padding: 16px;
  }

  .stock-item {
    padding: 14px;
  }

  .title {
    font-size: 20px;
  }
}
</style>